package tokenx

import (
	"time"

	"gitee.com/iece/common/errorx"

	"github.com/dgrijalva/jwt-go"
)

// 自定义一个字符串
var jwtKey = []byte("cccc")

type Claims struct {
	User      int64
	Org       int64
	TokenType int
	jwt.StandardClaims
}

// GetToken 颁发token
//
//	tokenType：
//		1  // pc登录
//		2  // 小程序登录
func GetToken(user int64, org int64, expireTime time.Time, tokenType int) (string, error) {
	claims := &Claims{
		User:      user,
		Org:       org,
		TokenType: tokenType,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), // 过期时间
			IssuedAt:  time.Now().Unix(),
			Issuer:    "rrs-saas",      // 签名颁发者
			Subject:   "account-token", // 签名主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

// ValidToken 解析token
func ValidToken(tokenString string) (int64, int64, int, error) {
	if tokenString == "" {
		return 0, 0, 0, errorx.NewParamError("token为空")
	}

	token, claims, err := ParseToken(tokenString)
	if err != nil || !token.Valid {
		return 0, 0, 0, err
	}
	return claims.User, claims.Org, claims.TokenType, nil
}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtKey, nil
	})
	return token, claims, err
}
